<?php
namespace App\Http\Controllers\Member;

use App\Models\Teaches;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\TeachesChapter;
use App\Models\TeachesContent;
use App\Models\Category;
use App\Models\TeachesContentPpt;
use App\Models\TeachesContentVideo;
use App\Models\TeachesContentOffice;
use Illuminate\Support\Facades\Log;
use App\Models\Tags;
use App\Models\TeachesTags;
use App\Models\SystemSetting;
use Illuminate\Support\Facades\Input;
/**
 *
 * @author Joker
 *        
 */
class TeachesController extends MemberController
{
    
    protected $catgory;
    
    public function __construct()
    {
        parent::__construct();
        $this->catgory = Category::where(array('app'=>'teaches','pid'=>0))->get();
    }
    
    public function index()
    {
        $sort = Input::get('sort',0);
        $query = Teaches::with('category')->where('user_id','=',$this->uid);
        switch ($sort){
            case 1:  //浏览量
                $query->orderBy("views_num",'desc');
                break;
            case 2:  //评论数
                $query->orderBy('comments_num','desc');
                break;
            default:
                $query->orderBy('created_at','desc');
        }
        $teaches = $query->paginate(10);

//        $teaches = Teaches::with('category')->where('user_id','=',$this->uid)->orderBy('created_at','desc')->paginate(10);
        return view('member.teaches.document')->with('documents',$teaches)->with('sort',$sort);
    }
    
    /**
     * 发布页面
     * @param Request $req
     */
    public function create(Request $req)
    {
        $type = $req->input('type','');
        $viewPath = '';
        switch ($type)
        {
            case 'step':
                $viewPath = 'member.teaches.step';
                break;
                default:
                    $viewPath = 'member.teaches.upload';
        }
        $array =array('dest_dir'=>'teaches','attachment'=>true,'_token'=>csrf_token());
        $options =  str_replace('"','\'',json_encode($array));
        $opts = base64_encode(serialize($array));
        return view($viewPath)
               ->with('type',$type)
               ->with('item',$this->item)
               ->with('category',$this->catgory) 
               ->with('options',$options)
               ->with('opts',$opts);
    }
    
    /**
     * 编辑
     * 文档
     */
    public function show($id)
    {
        if(empty($this->userinfo->company_id))
            return redirect(url('/company/center/companyinfo-default'));
        
        $array =array('dest_dir'=>'teaches','attachment'=>true,'_token'=>csrf_token());
        $options =  str_replace('"','\'',json_encode($array));
        $opts = base64_encode(serialize($array));
        $result = TeachesContent::with('attachment')->where(array('user_id'=>$this->uid,'id'=>$id))->first();
        if(empty($result)) abort(404);
        $newsTag = array();
        foreach ($result->tags as $tag)
        {
            $newsTag[] = Tags::where('tags_id','=',$tag->tags_id)->first()->tags_name;
        }
        switch ($result->teaches_type)
        {
            case '1':
                $documentid = $result->video->id;
                $documenttype = 'video';
                break;
            case '2':
                $documentid = $result->office->id;
                $documenttype = 'office';
                break;
            case '3':
                $documentid = $result->ppt->id;
                $documenttype = 'ppt';
                break;
            default:
                $documentid = 0;
                $documenttype = 'step';
                $result->description = unserialize($result->description);
                $result->content = unserialize($result->content);
                $result->notice = unserialize($result->notice);
                $result->tools = unserialize($result->tools);
                return view('company.step')
                        ->with('options',$options)
                        ->with('result',$result)
                        ->with('documenttype',$documenttype)
                        ->with('documentid',$documentid)
                        ->with('newstag',implode(",", $newsTag))
                        ->with('opts',$opts);
        }
        return view('company.upload')
                ->with('options',$options)
                ->with('result',$result)
                ->with('documenttype',$documenttype)
                ->with('documentid',$documentid)
                ->with('newstag',implode(",", $newsTag))
                ->with('opts',$opts);
    }
    
    /**
     * 保存
     * @param Request $req
     */
    public function store(Request $req) 
    {
        $this->validate($req, [
            'teachesname'   => 'required|max:255',
            'tdesc'         => 'required|min:20',
            'tnotice'       => 'required',
            'thumb'         => 'required',
        ]);
        $data = $req->only('documentid','url','documenttype','teachesname','chaptername','name','tdesc','tnotice','description','descimg','content','tools','notice',
            'thumb','tagsinput','price','teaches_id','chapter_id','content_id','type','child_1','level');
        if(empty($data['chaptername']))
            return $this->formatJson('error','所属章节不能为空！');
        if(empty($data['name']))
            return $this->formatJson('error','教程名称不能为空！');
        $teachesAttach = collect();
        switch ($data['documenttype'])
        {
            case 'ppt':
                $teachesAttach = TeachesContentPpt::find($data['documentid']);
                $data['teaches_type'] = 3;
                $description ='';
                $content= 'PPT教程';
                $tools = 'PPT教程';
                $notice ='';
                break;
            case 'video':
                $teachesAttach = TeachesContentVideo::find($data['documentid']);
                $data['teaches_type'] = 1;
                $description='';
                $content = '视频教程';
                $tools= '视频教程';
                $notice ='';
                break;
            case 'office':
                $teachesAttach =TeachesContentOffice::find($data['documentid']);
                $data['teaches_type'] = 2;
                $description ='';
                $content  = 'OFFFICE文档教程';
                $tools = 'OFFFICE文档教程';
                $notice ='';
                break;
            default :
                $data['teaches_type'] = 0;
                $description = serialize(array('name'=>$data['description'],'img'=>strToArray($data['descimg'],",")));
                $tools = serialize($data['tools']);
                $content= serialize(stepContent($data['content']));
                $notice = serialize($data['notice']);
        }
        $tagids = array();
        $tags = strToArray($data['tagsinput'], ",");
        if(empty($data['child_1']) || empty($data['type']))
        {
            return $this->formatJson('error','请选择分类！');
        }
        $category_id = $this->getTypes($data['type'], $data['child_1'], 0, 0);
        //敏感词过滤
        $sysword = SystemSetting::where('varname','=','sensitive_words')->first();
        $wordstr = unserialize($sysword['value']);
        $data['name']           = filter_words($data['name'], $wordstr);
        $description            = filter_words($description, $wordstr);
        $tools                  = filter_words($tools, $wordstr);
        $content                = filter_words($content, $wordstr);
        $notice                 = filter_words($notice, $wordstr);
        $data['chaptername']    = filter_words($data['chaptername'], $wordstr);
        $data['teachesname']    = filter_words($data['teachesname'], $wordstr);
        $data['tnotice']        = filter_words($data['tnotice'], $wordstr);
        $data['tdesc']          = filter_words($data['tdesc'], $wordstr);
        //教程数组
        $post = array(
            'name'        => $data['name'],
            'description' => $description,
            'tools'       => $tools,
            'content'     => $content,
            'notice'      => $notice,
            'user_id'     => $this->uid,
            'teaches_type'=> $data['teaches_type'],
            'price'       => $data['price']
        );
        //章节数据
        $chapterInsert = array(
            'name'      =>  $data['chaptername'],
            'user_id'   => $this->uid,
            'price'     => $data['price']
        );
        //课程数据
        $insertRow = array(
            'name'          => $data['teachesname'],
            'notice'        => $data['tnotice'],
            'description'   => $data['tdesc'],
            'thumb'         => $data['thumb'],
            'level'         => $data['level']?:0,
            'user_id'       => $this->uid,
            'cat_id'        => $category_id,
            'price'         => $data['price']
        );
        DB::beginTransaction();
        try{
            if($data['teaches_id'] && $data['teaches_id'] >0)
            {
                $teaches = Teaches::where(['user_id'=>$this->uid,'id'=>$data['teaches_id']])->first();
                if(empty($teaches))
                    return $this->formatJson('error','课程不存在！');
                $teaches->name          = $data['teachesname'];
                $teaches->cat_id        = $category_id;
                $teaches->description   = $data['tdesc'];
                $teaches->notice        = $data['tnotice'];
                $teaches->thumb         = $data['thumb'];
                $teaches->level         = $data['level'];
                $teaches->price         = $data['price'];
                if($data['chapter_id'] && $data['chapter_id']>0)
                {
                    $chapter = TeachesChapter::where(['teaches_id'=>$teaches->id,'id'=>$data['chapter_id'],'user_id'=>$this->uid])->first();
                    if(empty($chapter))
                        return $this->formatJson('error','章节不存在！');
                    $chapter->name = $data['chaptername'];
                    if($data['content_id'] && $data['content_id'] > 0)
                    {
                        $teachesContent = TeachesContent::where(['chapter_id'=>$chapter->id,'user_id'=>$this->uid])->first();
                        if(empty($teachesContent))
                            return $this->formatJson('error','教程不存在！');
                        if(intval($data['price']) > $teachesContent->price)
                        {
                            $chapter->price += intval($data['price']) - $teachesContent->price;
                            $teaches->price += intval($data['price']) - $teachesContent->price;
                        }
                        else
                        {
                            $chapter->price -= $teachesContent->price - intval($data['price']);
                            $teaches->price -= $teachesContent->price - intval($data['price']);
                        }
                        $teachesContent->name = $data['name'];
                        $teachesContent->description = $description;
                        $teachesContent->content = $content;
                        $teachesContent->notice = $notice;
                        $teachesContent->tools = $tools;
                        $teachesContent->price = $data['price'];
                        $this->otherInfo($teachesAttach, $teachesContent, $data['documenttype']);
                        $teachesContent->save();
                    }
                    else
                    {
                        $post['chapter_id'] = $chapter->id;
                        $teachesContent = TeachesContent::firstOrCreate($post);
                        $chapter->price += intval($data['price']); 
                        $teaches->price += intval($data['price']);
                    }
                    $chapter->save();
                }
                else 
                {
                    $chapterInsert['teaches_id'] = $teaches->id;
                    $chapter = TeachesChapter::firstOrCreate($chapterInsert);
                    $post['chapter_id'] = $chapter->id;
                    $teachesContent = TeachesContent::firstOrCreate($post);
                    $this->otherInfo($teachesAttach, $teachesContent, $data['documenttype']);
                }
                $teaches->save();
            }
            else
            {
                $teaches = Teaches::firstOrCreate($insertRow);
                $chapterInsert['teaches_id'] = $teaches->id;
                $chapter = TeachesChapter::firstOrCreate($chapterInsert);
                $post['chapter_id'] = $chapter->id;
                $teachesContent = TeachesContent::firstOrCreate($post);
                $this->otherInfo($teachesAttach, $teachesContent, $data['documenttype']);
            }
            foreach ($tags as $tg)
            {
                if(!empty(trim($tg)))
                {
                    $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                    $tagids[] = $tagsModel->tags_id;
                }
            }
            TeachesTags::where('teaches_id','=',$teaches->id)->delete();
            foreach ($tagids as $tgd){
                TeachesTags::firstOrCreate(['tags_id'=>$tgd,'teaches_id'=>$teaches->id]);
            }
            DB::commit();
        }catch (\PDOException $e){
            DB::rollback();
            Log::info(['职场技能课程'=>$e->getMessage()]);
            return $this->formatJson('error','数据异常！');
        }
        return $this->formatJson('success','发布文章成功！',$teaches,'/teaches/'.$teaches->id);
    }
    
    /**
     * 删除
     * @param integer $id
     */
    public function destroy($id) {
        $teaches = Teaches::where(array('user_id'=>$this->uid,'id'=>$id))->first();
        if(empty($teaches))
        {
            return  $this->formatJson('falied','抱歉，您要删除的文章不存在!');
        }
        else
        {
            DB::transaction(function() use ($teaches){
                $teaches->delete();
                TeachesContent::whereIn('chapter_id',TeachesChapter::where('teaches_id','=',$teaches->id)->lists('id'))->delete();
                TeachesChapter::where('teaches_id','=',$teaches->id)->delete();
            });
            return $this->formatJson('success','文章：［'.$teaches->name.'］ 删除成功');
        }
    }
    
    private function otherInfo($teachesAttach,$teaches,$documenttype)
    {
        if(!empty($teachesAttach))
        {
            switch ($documenttype)
            {
                case 'ppt':
                    if(count($teaches->ppt)>0)
                    {
                        $oldPptId = $teaches->ppt->id;
                        if($oldPptId != $teachesAttach->id)
                        {
                            $teachesAttach->content_id = $teaches->id;
                            TeachesContentPpt::where('id','=',$oldPptId)->delete();
                            $teachesAttach->save();
                        }
                    }
                    else
                    {
                        $teachesAttach->content_id = $teaches->id;
                        $teachesAttach->save();
                    }
                    break;
                case 'video':
                    if(count($teaches->video)>0)
                    {
                        $oldVideoId = $teaches->video->id;
                        if($oldVideoId != $teachesAttach->id)
                        {
                            $teachesAttach->content_id = $teaches->id;
                            TeachesContentVideo::where('id','=',$oldVideoId)->delete();
                            $teachesAttach->save();
                        }
                    }
                    else
                    {
                        $teachesAttach->content_id = $teaches->id;
                        $teachesAttach->save();
                    }
                    break;
                case 'office':
                    if(count($teaches->office)>0)
                    {
                        $oldOfficeId = $teaches->office->id;
                        if($oldOfficeId != $teachesAttach->id)
                        {
                            $teachesAttach->content_id = $teaches->id;
                            TeachesContentOffice::where("id",'=',$oldOfficeId)->delete();
                            $teachesAttach->save();
                        }
                    }
                    else
                    {
                        $teachesAttach->content_id = $teaches->id;
                        $teachesAttach->save();
                    }
                    break;
            }
        }
    }
}